package pinyinJava.executors;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pinyinJava.bean.DBean;
import pinyinJava.persistence.FilePer;
import pinyinJava.persistence.IFilePersistence;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class MyRun implements Runnable {

    private PyExecutor executor;
    private Element element;
    private Elements elements;
    private AtomicInteger atomicInteger;

    public MyRun(PyExecutor executor, Element element, Elements elements, AtomicInteger atomicInteger) {
        this.executor = executor;
        this.element = element;
        this.elements = elements;
        this.atomicInteger = atomicInteger;
    }

    @Override
    public void run() {
        ArrayList<DBean> words = new ArrayList<>();
        ArrayList<DBean> phrases = new ArrayList<>();
        for (Element element1 : elements) {
            if (element1.text().startsWith(element.text().toLowerCase())) {
                try {
                    executor.getWord(element1, words, phrases);
                } catch (IOException e) {
                    System.out.println("getWord Err:" + e == null ? "" : e.toString());
                }
            }
        }
        IFilePersistence filePersistence = new FilePer();
        if (words.size() > 0) {
            try {
                String path = String.format("%s%swords_%s.json", "pinyin-db" + File.separator, "word" + File.separator, element.text().toLowerCase());
                filePersistence.save(path, words);
            } catch (IOException e) {
                System.out.println("write2File word Err:" + e == null ? "" : e.toString());
            }
        }
        if (phrases.size() > 0) {
            try {
                String path = String.format("%s%sphrases_%s.json", "pinyin-db" + File.separator, "phrases" + File.separator, element.text().toLowerCase());
                filePersistence.save(path, phrases);
            } catch (IOException e) {
                System.out.println("write2File phrases Err:" + e == null ? "" : e.toString());
            }
        }
        atomicInteger.incrementAndGet();
    }
}
